package com.hy.myapp.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hy.myapp.mapper.ReputationMapper;

/**
 * 成名服务类
 * @author hy
 * @date 2021年10月24日
 */
@Service
public class ReputationService {
	private final static Logger logger = LoggerFactory.getLogger(ReputationService.class);
	
	@Autowired
	private ReputationMapper rptnMapper;
	
	/**
	 * 添加单个成名
	 * @param name
	 * @return
	 */
	public boolean addReputation(String name,long userId) {
		logger.info("Will add reputation={}",name);
		if(isReputationUnique(name)) {
			int changed=rptnMapper.add(name,userId);
			
			boolean retval=(changed==1);
			if(retval==true) {
				logger.info("Add reputation={} successfully.",name);
			}else {
				logger.info("Add reputation={} failed.",name);
			}
			
			return retval;
		}else {
			logger.info("Reputation:{} does exists.",name);
			return false;
		}
	}
	
	/**
	 * 添加成名及其描述
	 * @param name
	 * @param desc
	 * @param userId
	 * @return
	 */
	public boolean addReputation(String name,String desc,long userId) {
		logger.info("Will add reputation={} desc={}",name,desc);
		if(isReputationUnique(name)) {
			int changed=rptnMapper.add2(name,desc,userId);
			
			boolean retval=(changed==1);
			if(retval==true) {
				logger.info("Add reputation={} successfully.",name);
			}else {
				logger.info("Add reputation={} failed.",name);
			}
			
			return retval;
		}else {
			logger.info("Reputation:{} does exists.",name);
			return false;
		}
	}
	
	/**
	 * 判断成名是否唯一
	 * @param name
	 * @return
	 */
	private boolean isReputationUnique(String name) {
		return rptnMapper.count(name)==0;
	}
	
	/**
	 * 一次添加多个影星的成名
	 * @param multiNames 分隔符分隔的多名词
	 * @param delimiter 分隔符
	 * @return
	 */
	public int addMultiReputation(String multiNames,String delimiter,long userId) {
		String[] rawNames=multiNames.split("["+delimiter+"]");
		
		int inserted=0;
		for(String name:rawNames) {
			if(isReputationUnique(name)) {
				inserted+=rptnMapper.add(name,userId);
			}
		}
		
		return inserted;
	}
}
